<template>
  <div class="ai-analysis-page">
    <div class="header">
      <Header :url="userImageUrl" />
    </div>
    
    <div class="analysis-container">
      <div class="analysis-header">        <h2 class="analysis-title">
          🧠 AI学习分析报告
        </h2>
        <p class="analysis-subtitle">基于您的学习数据生成的个性化分析报告</p>
      </div>

      <div class="analysis-content">
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>AI正在分析您的学习数据，请稍候...</p>
        </div>        <div v-else-if="error" class="error-container">
          ⚠️
          <p>{{ error }}</p>
          <button @click="generateReport" class="retry-btn">重新生成</button>
        </div>

        <div v-else-if="analysisReport" class="report-content">
          <div class="report-card">
            <div class="report-text" v-html="formattedReport"></div>            <div class="report-actions">
              <button @click="generateReport" class="refresh-btn">
                🔄 重新生成报告
              </button>
              <button @click="exportReport" class="export-btn">
                📥 导出报告
              </button>
            </div>
          </div>
        </div>        <div v-else class="empty-state">
          📊
          <p>点击按钮生成您的AI学习分析报告</p>
          <button @click="generateReport" class="generate-btn">
            ✨ 生成分析报告
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import request from "../utils/request";

export default {
  name: "AILearningAnalysis",
  components: {
    Header
  },
  data() {
    return {
      loading: false,
      error: null,
      analysisReport: null
    };
  },
  computed: {
    userImageUrl() {
      return this.$store.getters.userImageUrl;
    },
    user() {
      return this.$store.state.user;
    },    formattedReport() {
      if (!this.analysisReport) return '';
      // 使用更完整的文本格式化方法
      return this.formatMessageText(this.analysisReport);
    }
  },
  created() {
    this.checkUser();
  },
  methods: {
    checkUser() {
      let userJson = localStorage.getItem("user");
      if (!userJson) {
        this.$router.push("/login");
        return;
      }
      let user = JSON.parse(userJson);
      this.$store.commit('setUser', user);
    },    async generateReport() {
      // 直接从 localStorage 获取用户信息，确保数据完整性
      let userJson = localStorage.getItem("user");
      if (!userJson) {
        this.error = "用户信息不存在，请重新登录";
        this.$router.push("/login");
        return;
      }
      
      let user;
      try {
        user = JSON.parse(userJson);
      } catch (error) {
        this.error = "用户信息格式错误，请重新登录";
        this.$router.push("/login");
        return;
      }

      console.log("完整用户信息:", user);
      
      if (!user || !user.userID || !user.targetBook) {
        this.error = "用户信息不完整，请重新登录";
        return;
      }

      this.loading = true;
      this.error = null;
      this.analysisReport = null;      try {
        const response = await request.post(`/statistic/analysis/${user.userID}/${user.targetBook}`);
        if (response.data) {
          this.analysisReport = response.data;
        } else {
          this.error = "分析报告生成失败，请稍后再试";
        }
      } catch (error) {
        console.error("生成分析报告失败:", error);
        this.error = error.response?.data?.msg || "分析报告生成失败，请稍后再试";
      } finally {
        this.loading = false;
      }
    },    exportReport() {
      if (!this.analysisReport) return;
      
      const element = document.createElement('a');
      const file = new Blob([this.analysisReport], { type: 'text/plain' });
      element.href = URL.createObjectURL(file);
      element.download = `AI学习分析报告_${new Date().toLocaleDateString()}.txt`;
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
    },

    // 格式化消息文本，处理think部分、括号提示文本、Markdown格式
    formatMessageText(text) {
      if (!text) return '';
      
      // 首先处理并移除think部分
      let processedText = this.removeThinkContent(text);
      
      // 渲染Markdown格式
      processedText = this.renderMarkdown(processedText);
      
      // 处理括号中的提示文本，如: *(Remember, you can tell me about your day!)*
      // 移除外层括号和星号，并用不同颜色显示
      processedText = processedText.replace(/\*?\(([^)]+)\)\*?/g, (match, content) => {
        return `<span class="hint-text">${content}</span>`;
      });
      
      return processedText;
    },

    // 自定义Markdown渲染方法
    renderMarkdown(text) {
      if (!text) return '';
      
      let html = text;
      
      // 预处理：去掉行首和行尾多余的空格，但保留有意义的缩进
      html = html.split('\n').map(line => {
        // 如果是代码块或者有特殊缩进意义的行，保持原样
        if (line.match(/^```|^\s*[-*+]\s|^\s*\d+\.\s|^\s*>/)) {
          return line;
        }
        return line.trim();
      }).join('\n');
      
      // 1. 处理代码块 (```code```) - 首先处理以避免后续处理影响
      html = html.replace(/```([\s\S]*?)```/g, (match, code) => {
        return `<pre class="markdown-code-block"><code>${this.escapeHtml(code.trim())}</code></pre>`;
      });
      
      // 2. 处理行内代码 (`code`) - 在处理其他格式之前
      html = html.replace(/`([^`\n]+)`/g, (match, code) => {
        return `<code class="markdown-inline-code">${this.escapeHtml(code)}</code>`;
      });
      
      // 3. 处理表格 - 在处理其他格式之前
      html = this.renderTable(html);
      
      // 4. 处理标题 (# ## ###) - 必须在行首
      html = html.replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, title) => {
        const level = hashes.length;
        return `<h${level} class="markdown-heading markdown-h${level}">${title.trim()}</h${level}>`;
      });
      
      // 5. 处理粗体 (**text** 或 __text__)
      html = html.replace(/\*\*([^*\n]+?)\*\*/g, '<strong class="markdown-bold">$1</strong>');
      html = html.replace(/__([^_\n]+?)__/g, '<strong class="markdown-bold">$1</strong>');
      
      // 6. 处理斜体 (*text* 或 _text_) - 避免与粗体冲突
      html = html.replace(/(?<!\*)\*([^*\n]+?)\*(?!\*)/g, '<em class="markdown-italic">$1</em>');
      html = html.replace(/(?<!_)_([^_\n]+?)_(?!_)/g, '<em class="markdown-italic">$1</em>');
      
      // 7. 处理删除线 (~~text~~)
      html = html.replace(/~~([^~\n]+?)~~/g, '<del class="markdown-strikethrough">$1</del>');
      
      // 8. 处理链接 [text](url) - 在处理其他格式之后
      html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, 
        '<a href="$2" class="markdown-link" target="_blank" rel="noopener noreferrer">$1</a>');
      
      // 9. 处理引用 (> text) - 必须在行首
      html = html.replace(/^>\s*(.+)$/gm, '<blockquote class="markdown-blockquote">$1</blockquote>');
      
      // 10. 处理无序列表 (- 或 * 或 +) - 必须在行首
      html = html.replace(/^[\s]*[-*+]\s+(.+)$/gm, '<li class="markdown-list-item">$1</li>');
      // 将连续的列表项包装在ul中
      html = html.replace(/(<li class="markdown-list-item">.*?<\/li>)(\s*<li class="markdown-list-item">.*?<\/li>)*/g, 
        '<ul class="markdown-list">$&</ul>');
      
      // 11. 处理有序列表 (1. 2. 3.) - 必须在行首
      html = html.replace(/^[\s]*\d+\.\s+(.+)$/gm, '<li class="markdown-ordered-list-item">$1</li>');
      // 将连续的有序列表项包装在ol中
      html = html.replace(/(<li class="markdown-ordered-list-item">.*?<\/li>)(\s*<li class="markdown-ordered-list-item">.*?<\/li>)*/g, 
        '<ol class="markdown-ordered-list">$&</ol>');
      
      // 12. 处理分隔线 (--- 或 ***) - 必须在单独一行
      html = html.replace(/^(---+|\*\*\*+)$/gm, '<hr class="markdown-hr">');
      
      // 13. 优化的段落和换行处理
      // 首先清理多余的连续换行
      html = html.replace(/\n{3,}/g, '\n\n');
      
      // 将双换行转换为段落分隔符
      html = html.replace(/\n\n/g, '__PARAGRAPH_BREAK__');
      
      // 对于单个换行，只在特定情况下转换为<br>
      html = html.replace(/\n/g, (match, offset, string) => {
        const beforeMatch = string.substring(0, offset);
        const afterMatch = string.substring(offset + 1);
        
        // 如果在HTML标签内，保持换行
        if (beforeMatch.match(/<(table|ul|ol|pre|blockquote)[^>]*>(?![\s\S]*<\/\1>)/) ||
            afterMatch.match(/^[\s]*<\/(table|ul|ol|pre|blockquote)>/)) {
          return '\n';
        }
        
        // 如果前一行或后一行是空的，不需要<br>
        const beforeLines = beforeMatch.split(/(?:\n|__PARAGRAPH_BREAK__)/);
        const afterLines = afterMatch.split(/(?:\n|__PARAGRAPH_BREAK__)/);
        const lastLine = beforeLines[beforeLines.length - 1] || '';
        const nextLine = afterLines[0] || '';
        
        // 如果前一行或后一行为空，或者包含HTML块级元素，则不添加<br>
        if (!lastLine.trim() || !nextLine.trim() || 
            lastLine.match(/<\/(h[1-6]|div|table|ul|ol|blockquote|pre|hr|p)>/) ||
            nextLine.match(/^<(h[1-6]|div|table|ul|ol|blockquote|pre|hr|p)/) ||
            lastLine.match(/^\s*[-*+\d]+\.?\s/) || // 列表项
            nextLine.match(/^\s*[-*+\d]+\.?\s/)) {  // 列表项
          return ' '; // 用空格替代，在段落处理时会被清理
        }
        
        return '<br>';
      });
      
      // 处理段落分割
      const paragraphs = html.split('__PARAGRAPH_BREAK__');
      const processedParagraphs = paragraphs.map(para => {
        let trimmed = para.trim();
        if (!trimmed) return '';
        
        // 清理段落内多余的空格
        trimmed = trimmed.replace(/\s+/g, ' ');
        
        // 如果已经是块级元素，不需要包装在<p>中
        if (trimmed.match(/^<(h[1-6]|div|table|ul|ol|blockquote|pre|hr)/)) {
          return trimmed;
        }
        
        return `<p class="markdown-paragraph">${trimmed}</p>`;
      }).filter(para => para);
      
      html = processedParagraphs.join('');
      
      // 如果没有任何块级元素，包装整个内容
      if (!html.match(/<(p|h[1-6]|div|table|ul|ol|blockquote|pre|hr)/)) {
        html = `<p class="markdown-paragraph">${html}</p>`;
      }
      
      // 最终清理：移除多余的空格和换行
      html = html.replace(/\s+<\/p>/g, '</p>');
      html = html.replace(/<p[^>]*>\s+/g, match => match.replace(/\s+$/, ''));
      html = html.replace(/<br>\s*<br>/g, '<br>');
      html = html.replace(/\s+<br>/g, '<br>');
      html = html.replace(/<br>\s+/g, '<br>');
      
      return html;
    },
    
    // 处理Markdown表格的方法
    renderTable(text) {
      // 匹配表格模式：至少两行，第二行是分隔符行
      const tableRegex = /(?:^|\n)((?:\|[^\n]+\|\n)+)\|(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)*\n((?:\|[^\n]+\|\n?)*)/gm;
      
      return text.replace(tableRegex, (match, headerRow, separatorRow, _, bodyRows) => {
        // 解析表头
        const headers = headerRow.trim().split('\n')[0]
          .split('|')
          .filter(cell => cell.trim())
          .map(cell => cell.trim());
        
        // 解析对齐方式
        const alignments = separatorRow.split('|')
          .filter(cell => cell.trim())
          .map(cell => {
            const trimmed = cell.trim();
            if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center';
            if (trimmed.endsWith(':')) return 'right';
            return 'left';
          });
        
        // 解析数据行
        const rows = bodyRows.trim()
          .split('\n')
          .filter(row => row.trim())
          .map(row => 
            row.split('|')
              .filter(cell => cell.trim() || row.indexOf(cell) !== 0) // 保留空单元格，但不包括开头的空字符串
              .map(cell => cell.trim())
          );
        
        // 生成HTML表格
        let tableHtml = '<table class="markdown-table">';
        
        // 表头
        if (headers.length > 0) {
          tableHtml += '<thead class="markdown-table-head"><tr>';
          headers.forEach((header, index) => {
            const align = alignments[index] || 'left';
            tableHtml += `<th class="markdown-table-header" style="text-align: ${align}">${header}</th>`;
          });
          tableHtml += '</tr></thead>';
        }
        
        // 表体
        if (rows.length > 0) {
          tableHtml += '<tbody class="markdown-table-body">';
          rows.forEach(row => {
            if (row.length > 0) {
              tableHtml += '<tr>';
              row.forEach((cell, index) => {
                const align = alignments[index] || 'left';
                tableHtml += `<td class="markdown-table-cell" style="text-align: ${align}">${cell || ''}</td>`;
              });
              tableHtml += '</tr>';
            }
          });
          tableHtml += '</tbody>';
        }
        
        tableHtml += '</table>';
        return tableHtml;
      });
    },
    
    // HTML转义工具方法
    escapeHtml(text) {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    },
    
    // 移除think内容的方法
    removeThinkContent(text) {
      if (!text) return '';
      
      // 匹配并移除 <think>...</think> 标签及其内容
      const thinkRegex = /<think>[\s\S]*?<\/think>/gi;
      let cleanedText = text.replace(thinkRegex, '');
      
      // 匹配并移除 think> 开头的内容（处理不完整的think标签）
      const incompleteThinkRegex = /think>[\s\S]*?(?=\n\n|\n[A-Z]|$)/gi;
      cleanedText = cleanedText.replace(incompleteThinkRegex, '');
      
      // 清理多余的空白行
      cleanedText = cleanedText.replace(/\n\s*\n\s*\n/g, '\n\n');
      
      return cleanedText.trim();
    }
  }
};
</script>

<style scoped>
.ai-analysis-page {
  display: flex;
  flex-direction: column;
  background-color: rgb(239, 242, 245);
  min-height: 100vh;
}

.header {
  height: 50px;
}

.analysis-container {
  flex: 1;
  padding: 25px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.analysis-header {
  text-align: center;
  margin-bottom: 30px;
}

.analysis-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.analysis-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.analysis-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-container {
  text-align: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 40px;
  color: #e74c3c;
}

.error-container > :first-child {
  font-size: 48px;
  margin-bottom: 20px;
}

.retry-btn {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 15px;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #c0392b;
}

.report-content {
  width: 100%;
  padding: 30px;
}

.report-card {
  width: 100%;
}

.report-text {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
  line-height: 1.8;
  font-size: 16px;
  color: #333;
  margin-bottom: 25px;
  word-wrap: break-word;
}

/* Markdown样式 */
.hint-text {
  color: #6c757d;
  font-style: italic;
  font-size: 0.9em;
}

.markdown-heading {
  margin: 1.5em 0 0.5em 0;
  font-weight: bold;
}

.markdown-h1 { 
  font-size: 1.8em; 
  color: #2c3e50;
  border-bottom: 2px solid #667eea;
  padding-bottom: 0.3em;
}

.markdown-h2 { 
  font-size: 1.5em; 
  color: #34495e;
  border-bottom: 1px solid #bdc3c7;
  padding-bottom: 0.2em;
}

.markdown-h3 { 
  font-size: 1.3em; 
  color: #34495e;
}

.markdown-h4 { 
  font-size: 1.1em; 
  color: #34495e;
}

.markdown-h5 { 
  font-size: 1em; 
  color: #34495e;
}

.markdown-h6 { 
  font-size: 0.9em; 
  color: #34495e;
}

.markdown-bold {
  font-weight: bold;
  color: #2c3e50;
}

.markdown-italic {
  font-style: italic;
  color: #555;
}

.markdown-strikethrough {
  text-decoration: line-through;
  color: #999;
}

.markdown-link {
  color: #667eea;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.2s ease;
}

.markdown-link:hover {
  color: #5a6fd8;
  border-bottom-color: #5a6fd8;
}

.markdown-blockquote {
  margin: 1em 0;
  padding: 0.5em 1em;
  border-left: 4px solid #667eea;
  background: #f8f9fa;
  color: #666;
  font-style: italic;
}

.markdown-list {
  margin: 1em 0;
  padding-left: 1.5em;
}

.markdown-ordered-list {
  margin: 1em 0;
  padding-left: 1.5em;
}

.markdown-list-item,
.markdown-ordered-list-item {
  margin: 0.3em 0;
  line-height: 1.6;
}

.markdown-code-block {
  background: #2f3349;
  color: #fff;
  padding: 1em;
  border-radius: 6px;
  margin: 1em 0;
  overflow-x: auto;
}

.markdown-code-block code {
  background: none;
  color: inherit;
  padding: 0;
  font-family: 'Courier New', Consolas, monospace;
  font-size: 0.9em;
  line-height: 1.4;
}

.markdown-inline-code {
  background: #f1f3f4;
  color: #d73a49;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: 'Courier New', Consolas, monospace;
  font-size: 0.9em;
}

.markdown-table {
  border-collapse: collapse;
  margin: 1em 0;
  width: 100%;
  background: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.markdown-table-header {
  background: #667eea;
  color: white;
  padding: 0.8em;
  font-weight: bold;
  border-bottom: 2px solid #5a6fd8;
}

.markdown-table-cell {
  padding: 0.8em;
  border-bottom: 1px solid #e1e4e8;
}

.markdown-table-body tr:nth-child(even) {
  background: #f8f9fa;
}

.markdown-table-body tr:hover {
  background: #e8f2ff;
}

.markdown-hr {
  border: none;
  height: 2px;
  background: linear-gradient(to right, #667eea, #764ba2);
  margin: 2em 0;
  border-radius: 1px;
}

.markdown-paragraph {
  margin: 1em 0;
  line-height: 1.8;
}

.report-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.refresh-btn, .export-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.refresh-btn {
  background: #667eea;
  color: white;
}

.refresh-btn:hover {
  background: #5a6fd8;
  transform: translateY(-2px);
}

.export-btn {
  background: #28a745;
  color: white;
}

.export-btn:hover {
  background: #218838;
  transform: translateY(-2px);
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-state > :first-child {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.generate-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 15px 30px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 20px auto 0;
  transition: all 0.3s ease;
}

.generate-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

@media (max-width: 768px) {
  .analysis-container {
    padding: 15px;
  }
  
  .analysis-title {
    font-size: 24px;
  }
  
  .report-content {
    padding: 20px;
  }
  
  .report-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .refresh-btn, .export-btn {
    width: 100%;
    max-width: 200px;
    justify-content: center;
  }
}
</style>
